#include "meetingmanager.h"
#include <QDebug>

MeetingManager* MeetingManager::m_instance = nullptr;

MeetingManager::MeetingManager(QObject *parent) : QObject(parent) {}

MeetingManager* MeetingManager::instance() {
    if (!m_instance) {
        m_instance = new MeetingManager();
    }
    return m_instance;
}

QString MeetingManager::createMeeting() {
    Meeting meeting;
    meeting.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
    meeting.multicastIp = generateMulticastIp();
    meeting.multicastPort = generateMulticastPort();
    meetings.append(meeting);
    qDebug() << "会议创建成功：" << meeting.id << "组播地址：" << meeting.multicastIp << ":" << meeting.multicastPort;
    return meeting.id;
}

bool MeetingManager::joinMeeting(const QString &id, const QString &user) {
    for (int i = 0; i < meetings.size(); ++i) {
        if (meetings[i].id == id) {
            if (!meetings[i].participants.contains(user)) {
                meetings[i].participants.append(user);
                qDebug() << "用户加入会议：" << user << "会议ID：" << id;
                return true;
            }
            return false; // 用户已存在
        }
    }
    return false; // 会议ID无效
}

Meeting MeetingManager::getMeetingInfo(const QString &id) {
    for (const Meeting &meeting : meetings) {
        if (meeting.id == id) {
            return meeting;
        }
    }
    return Meeting(); // 返回空对象
}

QString MeetingManager::generateMulticastIp() {
    QString ip;
    do {
        int b1 = QRandomGenerator::global()->bounded(224, 240);
        int b2 = QRandomGenerator::global()->bounded(0, 256);
        int b3 = QRandomGenerator::global()->bounded(0, 256);
        int b4 = QRandomGenerator::global()->bounded(1, 256);
        ip = QString("%1.%2.%3.%4").arg(b1).arg(b2).arg(b3).arg(b4);
    } while (ip == "224.0.1.0");
    return ip;
}

int MeetingManager::generateMulticastPort() {
    int port = 8889 + meetings.size();
    if (port > 65535) port = 8889;
    return port;
}
//#include "meetingmanager.h"

//MeetingManager::MeetingManager(QObject *parent) : QObject(parent)
//{

//}
